import { ref, onMounted, watchEffect } from 'vue';
import { ElMessage } from 'element-plus';
import { useMeterStore } from '@/stores/meter';
import { formatDate } from '@/utils/date';

export function useMeterSearch({
    // 配置参数
    fetchApi, // 获取数据的API函数
    chartTitle = "用量趋势", // 图表标题
    dateRange = 2, // 默认天数范围
    extraParams = {}, // 额外的API参数
    transformResponse = null, // 响应数据转换函数
    yAxisField = 'value', // Y轴数据字段
    timeField = 'time', // 时间字段
    formatDatePattern = "yyyy-MM-dd HH:mm", // 日期格式化模式
    chartType = 'hourlytrend', // 图表类型
}) {
    const loading = ref(false);
    const filteredMeterList = ref([]);
    // 构造默认日期范围
    const selectedDate = ref([
        new Date(new Date().getTime() - dateRange * 24 * 60 * 60 * 1000).getTime(),
        new Date().getTime()
    ]);
    let option = ref(null);

    // 获取数据列表
    const getMeterList = async () => {
        loading.value = true;
        try {
            if (useMeterStore().currentMeter === null) {
                if (useMeterStore().treeDataForChart.length === 0) {
                    await useMeterStore().fetchMeterList();
                }
                useMeterStore().setCurrentMeter(useMeterStore().treeDataForChart[0]);
            }

            if (selectedDate.value && selectedDate.value.length === 2) {
                const [startDate, endDate] = selectedDate.value;
                const params = {
                    id: useMeterStore().currentMeter.id,
                    type: `${useMeterStore().currentMeter.type}`,
                    start_time: startDate,
                    end_time: endDate,
                    ...extraParams
                };

                const res = await fetchApi(params);

                if (res.code != 200) {
                    ElMessage.error(res.message);
                    console.error(res.message);
                    filteredMeterList.value = [];
                } else {
                    // 如果提供了转换函数，使用它处理响应数据
                    filteredMeterList.value = transformResponse
                        ? transformResponse(res)
                        : res.meter_readings || [];
                }
            } else {
                filteredMeterList.value = [];
            }
        } catch (error) {
            console.error('获取数据失败:', error);
            ElMessage.error('获取数据失败');
        } finally {
            loading.value = false;
        }
    };

    const updateChart = () => {
        // if (!mainChart || !filteredMeterList.value.length) return;

        try {
            let xAxisData = [];
            let seriesData = [];

            if (chartType === 'hourlytrend') {
                // 小时趋势图处理逻辑保持不变
                xAxisData = [...filteredMeterList.value.map(item =>
                    formatDate(item[timeField], formatDatePattern))].slice(1);

                seriesData = [...filteredMeterList.value.map((item, index) => {
                    if (index === 0) return null;
                    const usage = item[yAxisField] - filteredMeterList.value[index - 1][yAxisField];
                    return usage.toFixed(2);
                }).filter(item => item !== null)];
            } else {
                // 日期数据处理优化
                const startDate = new Date(selectedDate.value[0]);
                const endDate = new Date(selectedDate.value[1]);

                // 创建完整的日期范围数组
                const dateArray = [];
                const currentDate = new Date(startDate);

                while (currentDate <= endDate) {
                    dateArray.push(new Date(currentDate));
                    currentDate.setDate(currentDate.getDate() + 1);
                }

                // 将数据转换为Map以便快速查找
                const dataMap = new Map(
                    filteredMeterList.value.map(item => [
                        formatDate(item.time, 'yyyy-MM-dd'),
                        item.usage
                    ])
                );

                // 填充数据，确保每一天都有值
                dateArray.forEach(date => {
                    const formattedDate = formatDate(date, 'yyyy-MM-dd');
                    xAxisData.push(formattedDate);

                    // 如果该日期有数据则使用实际数据，否则使用null或0
                    const value = dataMap.get(formattedDate);
                    seriesData.push(value ? value.toFixed(2) : 0);
                });
            }
        } catch (error) {
            console.error('更新图表失败:', error);
        }
    };

    // 监听currentMeter变化更新图表
    watchEffect(() => {
        if (useMeterStore().currentMeter) {
            getMeterList();
        }
    });

    // 组件挂载时调用
    onMounted(() => {
        getMeterList();
    });

    // 手动调用数据刷新
    const handleDateChange = () => {
        getMeterList();
    };

    // 重置数据
    const resetFields = () => {
        getMeterList();
    };



    return {
        selectedDate,
        filteredMeterList,
        loading,
        option,
        handleDateChange,
        resetFields,
    };
}